package cn.gok.manage.service.impl;

import cn.gok.dao.*;
import cn.gok.manage.service.IOrderService;
import cn.gok.manage.web.vo.*;
import cn.gok.pojo.*;
import cn.gok.util.Const;
import cn.gok.util.FTPUtil;
import cn.gok.util.Generator13;
import cn.gok.util.ResultData;

import com.alipay.api.AlipayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.ExtendParams;
import com.alipay.demo.trade.model.GoodsDetail;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import com.alipay.demo.trade.utils.ZxingUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;


/**
 * @author: 鸭鸭
 * @ClassName:OrderServiceImpl
 * @Package:cn.gok.manage.service.impl
 * @Description:
 * @date: 2021/8/9
 * @time: 10:41
 */
@Service("orderService")
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ShippingMapper shippingMapper;
    @Autowired
    PayInfoMapper payInfoMapper;

    Order2VO order2VO = null;

    // 支付宝当面付2.0服务
    private static AlipayTradeService tradeService;

    static {
        /** 一定要在创建AlipayTradeService之前调用Configs.init()设置默认参数
         *  Configs会读取classpath下的zfbinfo.properties文件配置信息，如果找不到该文件则确认该文件是否在classpath目录
         */
        Configs.init("zfbinfo.properties");

        /** 使用Configs提供的默认参数
         *  AlipayTradeService可以使用单例或者为静态成员对象，不需要反复new
         */
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();

    }

    @Override
    public ResultData createOrderByShippingId(int userId, int shippingId) {
        List<Cart> carts = cartMapper.selectAllCheckedProducts(userId);
        BigDecimal cartTotalPrice = BigDecimal.valueOf(0);
        if (carts==null){
            return ResultData.fail("创建订单失败");
        }

        List<OrderItemVO> list = new ArrayList<>();
        //生成orderId
        long orderNo = new Generator13().make();
        for (Cart c : carts) {
            //根据购物车中的商品id获得商品的信息
            Product product = productMapper.queryProductById(c.getProductId());
            //添加订单详细信息
            OrderItem orderItem = new OrderItem();
            orderItem.setUserId(userId);
            orderItem.setOrderNo(orderNo);
            orderItem.setProductId(c.getProductId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getMainImage());
            orderItem.setCurrentUnitPrice(product.getPrice());
            orderItem.setQuantity(c.getQuantity());

            //计算总价！
            BigDecimal quantity = BigDecimal.valueOf((int) c.getQuantity());
            BigDecimal price = product.getPrice();
            BigDecimal totalPrice = quantity.multiply(price);

            orderItem.setTotalPrice(totalPrice);
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            if(orderItemMapper.insertSelective(orderItem)==0){
                return ResultData.fail("创建订单失败");
            }

            //计算购物车中所有勾选商品总价
            cartTotalPrice = cartTotalPrice.add(totalPrice);

            //展示商品详情信息OrderItemVO
            OrderItemVO orderItemVO = new OrderItemVO();
            orderItemVO.setOrderNo(orderItem.getOrderNo());
            orderItemVO.setProductId(orderItem.getProductId());
            orderItemVO.setProductName(orderItem.getProductImage());
            orderItemVO.setProductImage(orderItem.getProductImage());
            orderItemVO.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
            orderItemVO.setQuantity(orderItem.getQuantity());
            orderItemVO.setTotalPrice(orderItem.getTotalPrice());
            orderItemVO.setCreateTime(orderItem.getCreateTime());
            list.add(orderItemVO);

        }

        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setShippingId(shippingId);
        order.setPayment(cartTotalPrice);
        order.setPaymentType(1);
        order.setPostage(0);
        order.setStatus(10);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        //添加订单信息
        if(orderMapper.insertSelective(order)==0){
            return ResultData.fail("创建订单失败");
        }
        //返回订单详细信息

        OrderVO orderVO = new OrderVO();
        orderVO.setOrderNo(orderNo);
        orderVO.setPayment(order.getPayment());
        orderVO.setPaymentType(order.getPaymentType());
        orderVO.setPostage(order.getPostage());
        orderVO.setStatus(order.getStatus());
        orderVO.setPaymentTime(order.getPaymentTime());
        orderVO.setSendTime(order.getSendTime());
        orderVO.setEndTime(order.getEndTime());
        orderVO.setCloseTime(order.getCloseTime());
        orderVO.setCreateTime(order.getCreateTime());
        orderVO.setOrderItemVoList(list);
        orderVO.setShippingId(shippingId);

        return ResultData.createData(orderVO);

    }

    @Override
    public ResultData getCartOrderChecked(int userId) {
        List<Cart> carts = cartMapper.selectAllCheckedProducts(userId);
        BigDecimal cartTotalPrice = BigDecimal.valueOf(0);
        if (carts==null){
            return ResultData.fail("创建订单失败");
        }
        List<OrderItemVO> list = new ArrayList<>();
        for (Cart c : carts) {
            //根据购物车中的商品id获得商品的信息
            Product product = productMapper.queryProductById(c.getProductId());
            OrderItemVO orderItemVO = new OrderItemVO();
            //计算总价！
            BigDecimal quantity = BigDecimal.valueOf((int) c.getQuantity());
            BigDecimal price = product.getPrice();
            BigDecimal totalPrice = quantity.multiply(price);
            orderItemVO.setProductId(product.getId());
            orderItemVO.setProductName(product.getName());
            orderItemVO.setProductImage(product.getMainImage());
            orderItemVO.setCurrentUnitPrice(totalPrice);
            orderItemVO.setCreateTime(c.getCreateTime());

            cartTotalPrice.add(totalPrice);

            list.add(orderItemVO);
        }
        OrderProductVO orderProductVO = new OrderProductVO();
        orderProductVO.setOrderItemVOs(list);
        orderProductVO.setImageHost("http://img.happymmall.com/");
        orderProductVO.setProductTotalPrice(cartTotalPrice);

        return ResultData.createData(orderProductVO);
    }

    @Override
    public ResultData getOrderList(int userId, int pageNum,int pageSize) {
        PageHelper.startPage(pageNum, pageSize, true);
        if(userId+"" == null){
            return ResultData.fail_login("用户未登录，请登录");
        }
        //获取用户订单的信息
        List<Order> orders = orderMapper.selectAllOrdersByUserId(userId);
        List<OrderDetailVO> orderDetailVOs = new ArrayList<>();
        for(Order order :orders){
            long orderNo = order.getOrderNo();
            List<OrderItem> orderItems = orderItemMapper.selectAllOrderItemByOrderNo(orderNo);
            List<OrderItemVO> orderItemVOs= new ArrayList<>();
            for(OrderItem orderItem :orderItems){
                OrderItemVO orderItemVO = new OrderItemVO();
                orderItemVO.setOrderNo(orderItem.getOrderNo());
                orderItemVO.setProductId(orderItem.getProductId());
                orderItemVO.setProductName(orderItem.getProductName());
                orderItemVO.setProductImage(orderItem.getProductImage());
                orderItemVO.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
                orderItemVO.setQuantity(orderItem.getQuantity());
                orderItemVO.setTotalPrice(orderItem.getTotalPrice());
                orderItemVO.setCreateTime(orderItem.getCreateTime());

                orderItemVOs.add(orderItemVO);
            }
            OrderDetailVO orderDetailVO = new OrderDetailVO();
            orderDetailVO.setOrderNo(order.getOrderNo());
            orderDetailVO.setPayment(order.getPayment());
            orderDetailVO.setPaymentType(order.getPaymentType());
            if(order.getPaymentType()==1){
                orderDetailVO.setPaymentTypeDesc("在线支付");
            }
            orderDetailVO.setPostage(order.getPostage());
            orderDetailVO.setStatus(order.getStatus());
            if(order.getStatus()==0){
                orderDetailVO.setStatusDesc("已取消");
            }else if(order.getStatus()==10){
                orderDetailVO.setStatusDesc("未付款");
            }else if(order.getStatus()==20){
                orderDetailVO.setStatusDesc("已付款");
            }else if(order.getStatus()==40){
                orderDetailVO.setStatusDesc("已发货");
            }else if(order.getStatus()==50){
                orderDetailVO.setStatusDesc("交易成功");
            }else{
                orderDetailVO.setStatusDesc("交易关闭");
            }
            orderDetailVO.setPaymentTime(order.getPaymentTime());
            orderDetailVO.setSendTime(order.getSendTime());
            orderDetailVO.setCloseTime(order.getCloseTime());
            orderDetailVO.setCreateTime(order.getCreateTime());
            orderDetailVO.setOrderItemVOs(orderItemVOs);
            orderDetailVO.setImageHost("http://img.happymmall.com/");
            orderDetailVO.setShippingId(order.getShippingId());
            //根据收货地址Id获取收货地址详细信息
            Shipping shipping= shippingMapper.selectByPrimaryKey(order.getShippingId());
            orderDetailVO.setReceiverName(shipping.getReceiverName());
            orderDetailVOs.add(orderDetailVO);

        }
        //获得分页信息
        PageInfo<OrderDetailVO> pageInfo = new PageInfo<OrderDetailVO>(orderDetailVOs);
        OrderListVO orderListVO = new OrderListVO();

        orderListVO.setPageNum(pageNum);
        orderListVO.setPageSize(pageSize);
        orderListVO.setSize(pageInfo.getSize());
        orderListVO.setOrderBy(null);
        orderListVO.setStartRow(pageInfo.getStartRow());
        orderListVO.setEndRow(pageInfo.getEndRow());
        orderListVO.setTotal(pageInfo.getTotal());
        orderListVO.setPages(pageInfo.getPages());
        orderListVO.setRecords(pageInfo.getList());
        orderListVO.setFirstPage(pageInfo.getNavigateFirstPage());
        orderListVO.setPrePage(pageInfo.getPrePage());
        orderListVO.setNextPage(pageInfo.getNextPage());
        orderListVO.setLastPage(pageInfo.getNavigateLastPage());
        if(pageInfo.getPageNum()==1){
            orderListVO.setFirstPage(true);
            orderListVO.setHasPreviousPage(false);
        }else{
            orderListVO.setFirstPage(false);
            orderListVO.setHasPreviousPage(true);
        }
        if(pageInfo.getNavigateLastPage()==pageInfo.getPageNum()) {
            orderListVO.setLastPage(true);
            orderListVO.setHasNextPage(false);
        }else{
            orderListVO.setLastPage(false);
            orderListVO.setHasNextPage(true);
        }
        orderListVO.setNavigatePages(pageInfo.getNavigatePages());
        orderListVO.setNavigatepageNums(pageInfo.getNavigatepageNums());

        return ResultData.createData(orderListVO);
    }

    @Override
    public ResultData getOrderDetailByOrderNo(long orderNo) {
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        if(order==null){
            return ResultData.fail("没有找到订单");
        }
        //获取订单的信息
        List<OrderItem> orderItems = orderItemMapper.selectAllOrderItemByOrderNo(orderNo);
        List<OrderItemVO> orderItemVOs= new ArrayList<>();
        for(OrderItem orderItem :orderItems){
            OrderItemVO orderItemVO = new OrderItemVO();
            orderItemVO.setOrderNo(orderItem.getOrderNo());
            orderItemVO.setProductId(orderItem.getProductId());
            orderItemVO.setProductName(orderItem.getProductName());
            orderItemVO.setProductImage(orderItem.getProductImage());
            orderItemVO.setCurrentUnitPrice(orderItem.getCurrentUnitPrice());
            orderItemVO.setQuantity(orderItem.getQuantity());
            orderItemVO.setTotalPrice(orderItem.getTotalPrice());
            orderItemVO.setCreateTime(orderItem.getCreateTime());

            orderItemVOs.add(orderItemVO);
            }
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setOrderNo(order.getOrderNo());
        orderDetailVO.setPayment(order.getPayment());
        orderDetailVO.setPaymentType(order.getPaymentType());
        if(order.getPaymentType()==1){
            orderDetailVO.setPaymentTypeDesc("在线支付");
        }
        orderDetailVO.setPostage(order.getPostage());
        orderDetailVO.setStatus(order.getStatus());
        if(order.getStatus()==0){
            orderDetailVO.setStatusDesc("已取消");
        }else if(order.getStatus()==10){
            orderDetailVO.setStatusDesc("未付款");
        }else if(order.getStatus()==20){
            orderDetailVO.setStatusDesc("已付款");
        }else if(order.getStatus()==40){
            orderDetailVO.setStatusDesc("已发货");
        }else if(order.getStatus()==50){
            orderDetailVO.setStatusDesc("交易成功");
        }else{
            orderDetailVO.setStatusDesc("交易关闭");
        }
        orderDetailVO.setPaymentTime(order.getPaymentTime());
        orderDetailVO.setSendTime(order.getSendTime());
        orderDetailVO.setCloseTime(order.getCloseTime());
        orderDetailVO.setCreateTime(order.getCreateTime());
        orderDetailVO.setOrderItemVOs(orderItemVOs);
        orderDetailVO.setImageHost("http://img.happymmall.com/");
        orderDetailVO.setShippingId(order.getShippingId());
        //根据收货地址Id获取收货地址详细信息
        Shipping shipping= shippingMapper.selectByPrimaryKey(order.getShippingId());
        orderDetailVO.setReceiverName(shipping.getReceiverName());
        ShippingOrderVO shippingOrderVO = new ShippingOrderVO();
        shippingOrderVO.setReceiverName(shipping.getReceiverName());
        shippingOrderVO.setReceiverPhone(shipping.getReceiverPhone());
        shippingOrderVO.setReceiverMobile(shipping.getReceiverMobile());
        shippingOrderVO.setReceiverProvince(shipping.getReceiverProvince());
        shippingOrderVO.setReceiverCity(shipping.getReceiverCity());
        shippingOrderVO.setReceiverDistrict(shipping.getReceiverDistrict());
        shippingOrderVO.setReceiverAddress(shipping.getReceiverAddress());
        shippingOrderVO.setReceiverZip(shipping.getReceiverZip());
        orderDetailVO.setShippingOrderVO(shippingOrderVO);
        return ResultData.createData(orderDetailVO);
    }

    @Override
    public ResultData cancelOrderByOrderNo(long orderNo) {
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        if(order==null || order.getStatus()==0){
            return ResultData.fail("该用户没有此订单");
        }else{
            if(order.getStatus()==10){
                orderMapper.deleteByOrderNo(orderNo);
                orderItemMapper.deleteByOrderNo(orderNo);
                return ResultData.success();

            }else{
                return ResultData.fail("此订单已付款，无法被取消");
            }
        }
    }

    @Override
    public ResultData pay(String path,long orderNo) throws IOException {
        //获取订单基础信息
        Order order = orderMapper.selectOrderByOrderNo(orderNo);

        if(order==null){
            return ResultData.fail("订单不存在");
        }
        List<OrderItem> orderItems = orderItemMapper.selectAllOrderItemByOrderNo(orderNo);

        // (必填) 商户网站订单系统中唯一订单号，64个字符以内，只能包含字母、数字、下划线，
        // 需保证商户系统端不能重复，建议通过数据库sequence生成，
        String outTradeNo = String.valueOf(orderNo);

        // (必填) 订单标题，粗略描述用户的支付目的。如“xxx品牌xxx门店当面付扫码消费”
        String subject = "gok-mall小唐门店当面付扫码消费";

        // (必填) 订单总金额，单位为元，不能超过1亿元
        // 如果同时传入了【打折金额】,【不可打折金额】,【订单总金额】三者,则必须满足如下条件:【订单总金额】=【打折金额】+【不可打折金额】
        String totalAmount = order.getPayment().toString();

        // (可选) 订单不可打折金额，可以配合商家平台配置折扣活动，如果酒水不参与打折，则将对应金额填写至此字段
        // 如果该值未传入,但传入了【订单总金额】,【打折金额】,则该值默认为【订单总金额】-【打折金额】
        String undiscountableAmount = "0";

        // 卖家支付宝账号ID，用于支持一个签约账号下支持打款到不同的收款账号，(打款到sellerId对应的支付宝账号)
        // 如果该字段为空，则默认为与支付宝签约的商户的PID，也就是appid对应的PID
        String sellerId = "";

        // 订单描述，可以对交易或商品进行一个详细地描述，比如填写"购买商品2件共15.00元"
        int productNum = 0;
        for(OrderItem orderItem:orderItems){
            productNum += orderItem.getQuantity();
        }
        String body = "共购买商品"+productNum+"件，共"+order.getPayment()+"元";

        // 商户操作员编号，添加此参数可以为商户操作员做销售统计
        String operatorId = "test_operator_id";

        // (必填) 商户门店编号，通过门店号和商家后台可以配置精准到门店的折扣信息，详询支付宝技术支持
        String storeId = "test_store_id";

        // 业务扩展参数，目前可添加由支付宝分配的系统商编号(通过setSysServiceProviderId方法)，详情请咨询支付宝技术支持
        ExtendParams extendParams = new ExtendParams();
        extendParams.setSysServiceProviderId("2088100200300400500");

        // 支付超时，定义为120分钟
        String timeoutExpress = "120m";

        // 商品明细列表，需填写购买商品详细信息，
        List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
        for(OrderItem orderItem : orderItems){
            // 创建一个商品信息，参数含义分别为商品id（使用国标）、名称、单价（单位为分）、数量，如果需要添加商品类别，详见GoodsDetail
            GoodsDetail goods = GoodsDetail.newInstance(String.valueOf(orderItem.getProductId()),
                    orderItem.getProductName(),
                    orderItem.getCurrentUnitPrice().multiply(new BigDecimal(100)).longValue(),
                    orderItem.getQuantity());
            // 创建好一个商品后添加至商品明细列表
            goodsDetailList.add(goods);
        }


        // 创建扫码支付请求builder，设置请求参数
        AlipayTradePrecreateRequestBuilder builder = new AlipayTradePrecreateRequestBuilder()
                .setSubject(subject).setTotalAmount(totalAmount).setOutTradeNo(outTradeNo)
                .setUndiscountableAmount(undiscountableAmount).setSellerId(sellerId).setBody(body)
                .setOperatorId(operatorId).setStoreId(storeId).setExtendParams(extendParams)
                .setTimeoutExpress(timeoutExpress)
                .setNotifyUrl("http://4a3qwe.natappfree.cc/order/alipay_callback.do")//支付宝服务器主动通知商户服务器里指定的页面http路径,根据需要设置
                .setGoodsDetailList(goodsDetailList);

        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        switch (result.getTradeStatus()) {
            case SUCCESS:
                log.info("支付宝预下单成功: )");

                AlipayTradePrecreateResponse response = result.getResponse();
                dumpResponse(response);

                String filePath = path+"/qr-"+response.getOutTradeNo()+".png";


                String erweimaFileName = path+"/qr-"+response.getOutTradeNo()+".png";



                log.info("filePath:" + filePath);
                //支付宝提供的工具类，将二维码地址解析成二维码图片，并发送到的路径
                ZxingUtils.getQRCodeImge(response.getQrCode(), 256, filePath);

               /* FTPUtil ftpUtil= new FTPUtil();

                boolean isUploadFile = ftpUtil.uploadFile(new File(path, erweimaFileName));*/

                Map<String,Object> data = new HashMap<>();
                data.put("orderNo",response.getOutTradeNo());
                data.put("qrPath",response.getOutTradeNo()+"http:localhost:8080/imgs/"+erweimaFileName);

                return ResultData.createData(data);

            case FAILED:
                log.error("支付宝预下单失败!!!");
                return ResultData.fail("支付宝预下单失败!!!");

            case UNKNOWN:
                log.error("系统异常，预下单状态未知!!!");
                return ResultData.fail("系统异常，预下单状态未知!!!");

            default:
                log.error("不支持的交易状态，交易返回异常!!!");
                return ResultData.fail("不支持的交易状态，交易返回异常!!!");
        }

    }
    @Override
    public ResultData alipayCallback(Map<String ,String> params,int userId){
        Long out_trade_no = Long.parseLong(params.get("out_trade_no"));//获取交易的订单号
        BigDecimal total_amount= new BigDecimal(params.get("total_amount")); //获取交易的金额

        Order order = orderMapper.selectOrderByOrderNo(out_trade_no);


        if (order == null){
            return ResultData.fail("订单编号不对，忽略此次支付");
        }


        if (!total_amount.equals(order.getPayment())){
            return ResultData.fail("此次订单支付金额不对，忽略此次支付");
        }

        //如果上述验证都通过，则修改订单状态（修改为已付款），并将支付信息存入支付信息表中
        Order order1 = new Order();
        order1.setOrderNo(out_trade_no);
        order1.setStatus(20);
        order1.setPaymentTime(new Date());
        int i = orderMapper.updateByOrderNoSelective(order1);
        if(i > 0){
            PayInfo payInfo = new PayInfo();
            payInfo.setUserId(userId);
            payInfo.setOrderNo(out_trade_no);
            payInfo.setPayPlatform(1);

            payInfo.setPlatformNumber(params.get("trade_no"));

            payInfo.setPlatformStatus(params.get("trade_status"));
            payInfo.setCreateTime(new Date());
            payInfo.setUpdateTime(new Date());

            i = payInfoMapper.insertSelective(payInfo);
            if(i>0){
                return ResultData.success("支付成功");
            }
        }
        return  ResultData.fail("支付失败");

    }

    @Override
    public ResultData selectOrderPayStatus(long orderNo) {
        Order order = orderMapper.selectOrderByOrderNo(orderNo);
        if(order.getStatus()==0||order.getStatus()==10){
            return ResultData.createData(false);
        }
        return ResultData.createData(true);
    }

    // 简单打印应答
    private void dumpResponse(AlipayResponse response) {
        if (response != null) {
            log.info(String.format("code:%s, msg:%s", response.getCode(), response.getMsg()));
            if (StringUtils.isNotEmpty(response.getSubCode())) {
                log.info(String.format("subCode:%s, subMsg:%s", response.getSubCode(),
                        response.getSubMsg()));
            }
            log.info("body:" + response.getBody());
        }
    }

    @Override
    public ResultData getAllOrder(int pageNum, int pageSize,Long orderNo) {
/*
        List<Order> orders = orderMapper.queryAlloOrder();
        orderVO = new OrderVO();

        List<OrderDetailVO> orderVOS = new ArrayList<>();
        for (Order order : orders) {
            List<OrderItem> orderItems = orderItemMapper.queryOrderItemByOrderNo(order.getOrderNo());
            List<OrderItemVO> orderItemVOS=new ArrayList<>();
            OrderDetailVO orderDetailVO = new OrderDetailVO(order.getOrderNo(),order.getPayment(),order.getPaymentType(),
                    order.getPostage(),order.getStatus(),order.getPaymentTime(),order.getSendTime(),
                    order.getEndTime(),order.getCloseTime(),order.getCreateTime(),order.getShippingId());
            System.out.println(order);
            for (OrderItem orderItem : orderItems) {
                orderItemVOS.add(new OrderItemVO(orderItem));
                System.out.println(orderItem);
            }
            orderDetailVO.setOrderItems(orderItems);
            orderVO.setOrderDetailVO(orderDetailVO);
            if (order != null){
                return ResultData.createData(orderVO);
            }
            return ResultData.fail("用户未登录,请登录");
        }
        return ResultData.fail("没有权限");
*/


        List<Order> orders = orderMapper.queryAlloOrder();
        order2VO = new Order2VO();
        List<OrderDetail2VO>  orderDetail2VO = new ArrayList<>();
        for (Order order : orders) {

            OrderDetail2VO orderDetail2VO1 = new OrderDetail2VO(order.getOrderNo(),order.getPayment(),order.getPaymentType(),
                    order.getPostage(),order.getStatus(),order.getPaymentTime(),order.getSendTime(),
                    order.getEndTime(),order.getCloseTime(),order.getCreateTime(),order.getShippingId());
            List<OrderItem> orderItems = orderItemMapper.queryOrderItemByOrderNo(order.getOrderNo());
            List<OrderItem> orderItems1 = new ArrayList<>();
            for (OrderItem orderItem : orderItems) {
                orderItems1.add(orderItem);
                orderDetail2VO1.setOrderItems(orderItems1);
            }
            orderDetail2VO.add(orderDetail2VO1);
            order2VO.setOrderDetail2VOS(orderDetail2VO);

        }
        if ( order2VO != null){
            return ResultData.createData(order2VO);
        }
        return ResultData.fail("用户未登录,请登录");
    }

    @Override
    public ResultData queryOrderByOrderNo(long orderNo) {
        Order order = orderMapper.queryOrderbyOrderNo(orderNo);
        List<OrderItem> orders = orderItemMapper.queryOrderItemByOrderNo(orderNo);

        order2VO = new Order2VO();
//        orderItemVO = new OrderItemVO();

        order2VO.setOrder(order);
        order.setOrderItemsList(orders);
        if (order != null && orders != null){
            return ResultData.createData(order2VO);
        }
        return ResultData.fail("没有找到订单");

    }

    @Override
    public ResultData queryOrderDetailByOrderNo(long orderNo) {
        Order order = orderMapper.queryOrderbyOrderNo(orderNo);


        List<OrderItem> orderItems = orderItemMapper.queryOrderItemByOrderNo(orderNo);


        String shipping = shippingMapper.queryReceiverNameByOrderNo(orderNo);


        List<Shipping> shipping1 = shippingMapper.queryAllByOrderNo(orderNo);


        OrderDetail2VO orderDetail2VO = new OrderDetail2VO(order.getOrderNo(),order.getPayment(),order.getPaymentType(),order.getPostage(),order.getStatus(),order.getPaymentTime(),order.getSendTime(),order.getEndTime(),order.getCloseTime(),order.getCreateTime(),order.getShippingId());
        orderDetail2VO.setOrderItems(orderItems);
        orderDetail2VO.setReceiverName(shipping);
        orderDetail2VO.setShippings(shipping1);

        if (order != null){
            return ResultData.createData(orderDetail2VO);
        }
        return ResultData.fail("没有找到订单");
    }

    @Override
    public ResultData sendGoods(long order) {
        int i = orderMapper.sendGoods(order);
        if (i > 0){
            return ResultData.success("发货成功");
        }
        return ResultData.fail("发货失败");
    }



}

